package com.fzhucc.modules.elect.service;

import com.fzhucc.config.FileProperties;
import com.fzhucc.exception.BadRequestException;
import com.fzhucc.modules.elect.domain.ElectClassify;
import com.fzhucc.modules.elect.domain.dto.ElectAddDto;
import com.fzhucc.modules.elect.domain.dto.ElectDto;
import com.fzhucc.modules.elect.domain.dto.ElectEditDto;
import com.fzhucc.modules.elect.domain.dto.ElectQueryCriteria;
import com.fzhucc.modules.elect.repository.ElectClassifyRepository;
import com.fzhucc.modules.elect.service.mapstruct.ElectMapper;
import com.fzhucc.modules.fenRecordLog.service.FenRecordLogService;
import com.fzhucc.modules.live.domain.dto.LiveQueryCriteria;
import com.fzhucc.modules.notice.domain.Elect;
import com.fzhucc.modules.system.domain.User;
import com.fzhucc.modules.system.repository.UserRepository;
import com.fzhucc.modules.system.service.UserService;
import com.fzhucc.modules.system.service.dto.UserDto;
import com.fzhucc.utils.*;
import lombok.RequiredArgsConstructor;
import com.fzhucc.modules.notice.repository.ElectRepository;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

/**
 * @author yyg
 * @website https://eladmin.vip
 * @description 服务实现
 * @date 2022-11-16
 **/
@Service
@RequiredArgsConstructor
public class ElectService {

    private final ElectRepository noticeRepository;

    private final ElectClassifyRepository electClassifyRepository;
    private final ElectMapper noticeMapper;

    private final UserService userService;

    private final FileProperties properties;

    private final FenRecordLogService fenRecordLogService;

    private final UserRepository userRepository;

    @Value("${org.area.all}")
    public String all;

    @Value("${org.area.all2}")
    public String all2;

    @Value("${fen.type.ty}")
    public String ty;

/*    //根据不同设置不同的部门查看
    public String setCriteria(ElectQueryCriteria criteria) {
        Long userId = null;
        try {
            userId = SecurityUtils.getCurrentUserId();
        } catch (Exception e) {
            //throw new RuntimeException(e);
            String orgArea = criteria.getOrgArea();
            if (orgArea != null && orgArea.equals(all)) { //如果等于福建省则查全部
                return null;
            }
        }
        if (userId != null) {
            Optional<User> userOptional = userRepository.findById(userId);
            User res = userOptional.get();
            if (res.getOrgArea() != null && (res.getOrgArea().equals(all) || res.getOrgArea().equals(all2))) {//用的org组织最高看全部
                return null;
            } else {
                return res.getOrgArea();//如果用户的权限不是福建省则 只能看到对应的组织
            }
        } else {
            return null;
        }
    }

    public String orgAreaReturn() {
        Long userId = SecurityUtils.getCurrentUserId();
        if (userId == null) {//未登录则外面传进来
            return "";
        } else {
            Optional<User> userOptional = userRepository.findById(userId);
            User res = userOptional.get();
            return res.getOrgArea();
        }
    }*/

    public Map<String, Object> queryAll(ElectQueryCriteria criteria, Pageable pageable) {
        /*if (criteria.getOrgArea() != null && !criteria.getOrgArea().equals("")) {
            //h5的直接传orgArea
            if (criteria.getOrgArea().equals(all)) {
                criteria.setOrgArea(null);
                if (criteria.getOrgAreas() != null && criteria.getOrgAreas().length > 0) {
                    //TODO 即查询参数有参数  省总账号查具体模糊查询
                    String[] orgAreas = criteria.getOrgAreas();
                    criteria.setOrgArea(orgAreas[orgAreas.length - 1]);
                }
            }
        } else {
            //管理端根据登录用户地区
            criteria.setOrgArea(setCriteria(criteria));
            if (criteria.getOrgAreas() != null && criteria.getOrgAreas().length > 0) {
                //TODO 即查询参数有参数  省总账号查具体模糊查询
                String[] orgAreas = criteria.getOrgAreas();
                //传参要查的 orgArea
                String csOrgArea = orgAreas[orgAreas.length - 1];
                //登录用户的 orgArea
                String dlOrgArea = criteria.getOrgArea();
                if (dlOrgArea == null) { //表示省总
                    criteria.setOrgArea(csOrgArea);
                } else {
                    //不是省总  登录的 存在  传进来的全部 则可以 否则则使用登录的
                    String[] split = dlOrgArea.split(";");
                    if (split.length == 1) {
                        //表示为省
                        if (split[0].equals(all)) {
                            criteria.setOrgArea(csOrgArea);
                        } else {
                            //其他省 则 传进来的第一个和这个省一致才返回数据
                            String orgArea = orgAreas[0];
                            if (split[0].equals(orgArea)) {
                                criteria.setOrgArea(csOrgArea);
                            } else {
                                criteria.setOrgArea(dlOrgArea);
                            }
                        }
                    }
                    if (split.length == 2) {
                        //例 ： 福建省;福州市;
                        String s = split[1];
                        if (orgAreas.length == 3) {
                            //福建省;福州市;马尾区;
                            String orgArea = orgAreas[1];
                            if (s.equals(orgArea)) {
                                //福州市相同的情况
                                criteria.setOrgArea(csOrgArea);
                            } else {
                                criteria.setOrgArea(dlOrgArea);
                            }
                        }
                        if (orgAreas.length == 2) {
                            //福建省;福州市;
                            String orgArea = orgAreas[1];
                            if (s.equals(orgArea)) {
                                //福州市相同的情况
                                criteria.setOrgArea(csOrgArea);
                            } else {
                                criteria.setOrgArea(dlOrgArea);
                            }
                        }
                    }
                    if (split.length == 3) {
                        //例 ： 福建省;福州市;马尾区;  相符就查马尾区  不相符就查登录用户的区域
                        String s = split[2];
                        if (s.equals(csOrgArea)) {
                            criteria.setOrgArea(csOrgArea);
                        } else {
                            criteria.setOrgArea(dlOrgArea);
                        }
                    }
                }
            }
        }*/
        //TODO 增加访问分数
        try {
            fenRecordLogService.insertUserFen(ty);
        } catch (Exception e) {

        }

        if (criteria.getOrgArea() != null && criteria.getOrgArea().equals("福建省")) {
            criteria.setOrgArea(null);
        }
        Page<Elect> page = noticeRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        Page<ElectDto> map = page.map(noticeMapper::toDto);
        List<ElectDto> list = map.getContent();
        if (list != null) {
            for (int i = 0; i < list.size(); i++) {
                ElectDto dto = list.get(i);
                if (dto != null) {
                    Long createUserId = dto.getCreateUserId();
                    if (createUserId != null) {
                        UserDto userDto = userService.findById(createUserId);
                        if (userDto != null) {
                            dto.setCreateUser(userDto);
                        }
                    }

                    String pic = dto.getPic();
                    if (pic != null && pic.contains(";")) {
                        String[] array = pic.split(";");
                        dto.setPics(array);
                    } else {
                        String[] array = {};
                        dto.setPics(array);
                    }

                    String key = dto.getKeyWord();
                    if (key != null && key.contains(";")) {
                        String[] array = key.split(";");
                        dto.setKeyWords(array);
                    } else {
                        String[] array = {};
                        dto.setKeyWords(array);
                    }

                    /*String orgArea = dto.getOrgArea();
                    if (orgArea != null && orgArea.contains(";")) {
                        String[] array = orgArea.split(";");
                        dto.setOrgAreas(array);
                    } else {
                        String[] array = {};
                        dto.setOrgAreas(array);
                    }*/
                }
            }
        }
        return PageUtil.toPage(map);
    }

    public List<ElectDto> queryAll(ElectQueryCriteria criteria) {
        return noticeMapper.toDto(noticeRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    public ElectDto findById(Integer id) {
        //TODO 增加访问分数
        try {
            fenRecordLogService.insertUserFen(ty);
        } catch (Exception e) {

        }

        Elect notice = noticeRepository.findById(id).orElseGet(Elect::new);
        ValidationUtil.isNull(notice.getId(), "Notice", "id", id);
        ElectDto electDto = noticeMapper.toDto(notice);
        String pic = electDto.getPic();
        if (pic != null && pic.contains(";")) {
            String[] array = pic.split(";");
            electDto.setPics(array);
        } else {
            String[] array = {};
            electDto.setPics(array);
        }
        String key = electDto.getKeyWord();
        if (key != null && key.contains(";")) {
            String[] array = key.split(";");
            electDto.setKeyWords(array);
        } else {
            String[] array = {};
            electDto.setKeyWords(array);
        }
        /*String orgArea = electDto.getOrgArea();
        if (orgArea != null && orgArea.contains(";")) {
            String[] array = orgArea.split(";");
            electDto.setOrgAreas(array);
        } else {
            String[] array = {};
            electDto.setOrgAreas(array);
        }*/
        return electDto;
    }

    @Transactional(rollbackFor = Exception.class)
    public ElectDto create(ElectAddDto noticeAddDto) {
        Elect resources = new Elect();
        Long userId = SecurityUtils.getCurrentUserId();
        if (userId == null) {
            throw new BadRequestException("用户ID未找到");
        }
        resources.setCreateUserId(userId);
        resources.setTitle(noticeAddDto.getTitle());
        resources.setBanner(noticeAddDto.getBanner());
        resources.setReleaseTime(noticeAddDto.getReleaseTime());
        resources.setReleaseUnit(noticeAddDto.getReleaseUnit());
        resources.setContent(noticeAddDto.getContent());
        resources.setIsIndex(noticeAddDto.getIsIndex());
        resources.setSort(noticeAddDto.getSort());
        resources.setVideo(noticeAddDto.getVideo());
        if (noticeAddDto.getPics() != null && noticeAddDto.getPics().length > 0) {
            String last = "";
            for (String a : noticeAddDto.getPics()) {
                last = last + a + ";";
            }
            resources.setPic(last);
        } else {
            resources.setPic(null);
        }
        if (noticeAddDto.getKeyWords() != null && noticeAddDto.getKeyWords().length > 0) {
            String last = "";
            for (String a : noticeAddDto.getKeyWords()) {
                last = last + a + ";";
            }
            resources.setKeyWord(last);
        } else {
            resources.setKeyWord(null);
        }
        /*if (noticeAddDto.getOrgAreas() != null && noticeAddDto.getOrgAreas().length > 0) {
            //外部传
            String last = "";
            for (String a : noticeAddDto.getOrgAreas()) {
                last = last + a + ";";
            }
            resources.setOrgArea(last);
        } else {
            //根据登录用户 orgArea进行判断
            resources.setOrgArea(orgAreaReturn());
        }*/
        resources.setCx(noticeAddDto.getCx());
        resources.setClassify(noticeAddDto.getClassify());
        List<ElectClassify> byName = electClassifyRepository.findByName("%" + noticeAddDto.getClassify() + "%");
        if (byName == null) {
            resources.setOrgArea("福州市"); //没有就默认福州市
        }
        if (byName.size() != 1) {
            resources.setOrgArea("福州市"); //没有就默认福州市
        } else {
            resources.setOrgArea(byName.get(0).getOrgArea());
        }
        resources.setIntro(noticeAddDto.getIntro());
        //resources.setOrgArea(orgAreaReturn());
        //resources.setOrgArea(orgAreaReturnIfHave(noticeAddDto.getOrgArea()));
        resources.setIsShow(noticeAddDto.getIsShow());
        resources.setType(noticeAddDto.getType());
        resources.setContentUrl(noticeAddDto.getContentUrl());
        return noticeMapper.toDto(noticeRepository.save(resources));
    }

    @Transactional(rollbackFor = Exception.class)
    public void update(ElectEditDto noticeEditDto) {
        Elect resources = new Elect();
        Long userId = SecurityUtils.getCurrentUserId();
        if (userId == null) {
            throw new BadRequestException("用户ID未找到");
        }
        resources.setId(noticeEditDto.getId());
        resources.setCreateUserId(userId);
        resources.setTitle(noticeEditDto.getTitle());
        resources.setBanner(noticeEditDto.getBanner());
        resources.setReleaseTime(noticeEditDto.getReleaseTime());
        resources.setReleaseUnit(noticeEditDto.getReleaseUnit());
        resources.setContent(noticeEditDto.getContent());
        resources.setClassify(noticeEditDto.getClassify());
        List<ElectClassify> byName = electClassifyRepository.findByName("%" + noticeEditDto.getClassify() + "%");
        if (byName == null) {
            resources.setOrgArea("福州市"); //没有就默认福州市
        }
        if (byName.size() != 1) {
            resources.setOrgArea("福州市"); //没有就默认福州市
        } else {
            resources.setOrgArea(byName.get(0).getOrgArea());
        }
        resources.setSort(noticeEditDto.getSort());
        resources.setIsIndex(noticeEditDto.getIsIndex());
        resources.setIntro(noticeEditDto.getIntro());
        resources.setVideo(noticeEditDto.getVideo());
        if (noticeEditDto.getPics() != null && noticeEditDto.getPics().length > 0) {
            String last = "";
            for (String a : noticeEditDto.getPics()) {
                last = last + a + ";";
            }
            resources.setPic(last);
        } else {
            resources.setPic(null);
        }
        if (noticeEditDto.getPics() != null && noticeEditDto.getPics().length == 0) {
            resources.setPic("");
        }

        if (noticeEditDto.getKeyWords() != null && noticeEditDto.getKeyWords().length > 0) {
            String last = "";
            for (String a : noticeEditDto.getKeyWords()) {
                last = last + a + ";";
            }
            resources.setKeyWord(last);
        } else {
            resources.setKeyWord(null);
        }
        if (noticeEditDto.getKeyWords() != null && noticeEditDto.getKeyWords().length == 0) {
            resources.setKeyWord("");
        }
        resources.setCx(noticeEditDto.getCx());
        //resources.setOrgArea(orgAreaReturn());
        //resources.setOrgArea(orgAreaReturnIfHave(noticeEditDto.getOrgArea()));
        resources.setIsShow(noticeEditDto.getIsShow());
        resources.setType(noticeEditDto.getType());
        resources.setContentUrl(noticeEditDto.getContentUrl());
        /*if (noticeEditDto.getOrgAreas() != null && noticeEditDto.getOrgAreas().length > 0) {
            //外部传
            String last = "";
            for (String a : noticeEditDto.getOrgAreas()) {
                last = last + a + ";";
            }
            resources.setOrgArea(last);
        } else {
            //根据登录用户 orgArea进行判断
            resources.setOrgArea(orgAreaReturn());
        }*/
        Elect notice = noticeRepository.findById(resources.getId()).orElseGet(Elect::new);
        ValidationUtil.isNull(notice.getId(), "Notice", "id", resources.getId());
        notice.copy(resources);
        noticeRepository.save(notice);
    }

    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            noticeRepository.deleteById(id);
        }
    }

    public void download(List<ElectDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (ElectDto notice : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("标题", notice.getTitle());
            map.put("banner图", notice.getBanner());
            map.put("发布时间", notice.getReleaseTime());
            map.put("发文单位", notice.getReleaseUnit());
            map.put("内容", notice.getContent());
            map.put("显示顺序", notice.getSort());
            map.put("简介", notice.getIntro());
            map.put("是否展示小程序", notice.getIsShow());
            map.put("是否首页展示", notice.getIsIndex());
            map.put("创建者user_id", notice.getCreateUserId());
            map.put("内容分类", notice.getType());
            map.put("内容链接", notice.getContentUrl());
            map.put("区域划分", notice.getOrgArea());
            map.put("优选分类", notice.getClassify());
            map.put("视频", notice.getVideo());
            map.put("图片", notice.getPic());
            map.put("关键字", notice.getKeyWord());
            map.put("创新点", notice.getCx());
            //map.put("地区组织机构区分  ", notice.getOrgArea());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    public Map<String, String> douploadpic(MultipartFile multipartFile, Integer id) {
        // 文件大小验证
        FileUtil.checkSize(properties.getAvatarMaxSize(), multipartFile.getSize());
        // 验证文件上传的格式
        String image = "gif jpg png jpeg";
        String fileType = FileUtil.getExtensionName(multipartFile.getOriginalFilename());
        if (fileType != null && !image.contains(fileType)) {
            throw new BadRequestException("文件格式错误！, 仅支持 " + image + " 格式");
        }
        Optional<Elect> res = noticeRepository.findById(id);
        if (res.isPresent()) {
            Elect notice = res.orElseGet(() -> new Elect());
            String oldPath = notice.getBanner();
            File file = FileUtil.upload(multipartFile, properties.getBanner());
            String path = Objects.requireNonNull(file).getPath();
            String[] files = path.split("file");
            res.get().setBanner("/file" + files[1]);
            noticeRepository.save(res.get());
            if (StringUtils.isNotBlank(oldPath)) {
                FileUtil.del(oldPath);
            }
            return new HashMap<String, String>(1) {{
                put("banner", file.getName());
            }};
        }
        return new HashMap<String, String>(1) {{
            put("banner", "fail");
        }};
    }
}